package edu.ynu.se.xiecheng.achitectureclass.common.utils;

import edu.ynu.se.xiecheng.achitectureclass.common.dto.CommonDeviceTokenResponseDTO;
import okhttp3.*;
import com.google.gson.Gson;

import java.io.IOException;

public class CommonDeviceTokenUtil {

    private static final String TOKEN_URL = "https://fbox360.com/idserver/core/connect/token";
    private static final String SCOPE = "fbox";
    private static final String CLIENT_ID = "68db2e8bda8d47b5b5db7eaf71c7dcdd";
    private static final String CLIENT_SECRET = "76dc724c95004acab25482d344dab407";
    private static final String GRANT_TYPE = "client_credentials";

    private static final MediaType MEDIA_TYPE = MediaType.parse("application/x-www-form-urlencoded");

    public static CommonDeviceTokenResponseDTO getToken() throws IOException {
        OkHttpClient client = new OkHttpClient();
        Gson gson = new Gson();

        while (true) {
            try {
                RequestBody formBody = new FormBody.Builder()
                        .add("scope", SCOPE)
                        .add("client_id", CLIENT_ID)
                        .add("client_secret", CLIENT_SECRET)
                        .add("grant_type", GRANT_TYPE)
                        .build();

                Request request = new Request.Builder()
                        .url(TOKEN_URL)
                        .post(formBody)
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                    String responseBody = response.body().string();
                    return gson.fromJson(responseBody, CommonDeviceTokenResponseDTO.class);
                }
            } catch (IOException e) {
                try {
                    Thread.sleep(500); // 等待0.5秒
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new IOException("Thread interrupted", ie);
                }
            }
        }
    }

}
